﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mvvm;
using System.Collections.ObjectModel;
using System.Windows;
using System.Diagnostics;
using Microsoft.VisualBasic.Devices;
using CodeIn.Ui;
using System.Timers;
using System.Threading;

namespace CodeIn.Modules.Misc.SystemInfo {
	public class SystemInfoViewModel : BaseViewModel {
		public ObservableCollection<Point> CpuPoints { get; private set; }
		public ObservableCollection<Point> RamPoints { get; private set; }

		public double TotalPhysicalMemory { get; private set; }
		public bool IsEnabled { get; set; }

		public SystemInfoViewModel() {
			CpuPoints = new ObservableCollection<Point>();
			RamPoints = new ObservableCollection<Point>();
			IsEnabled = true;

			// Add CPU counter
			PerformanceCounter cpuCounter = new PerformanceCounter();
			cpuCounter.CategoryName = "Processor";
			cpuCounter.CounterName = "% Processor Time";
			cpuCounter.InstanceName = "_Total";

			// Add RAM counter
			PerformanceCounter ramCounter = new PerformanceCounter();
			var computerInfo = new ComputerInfo();
			TotalPhysicalMemory = computerInfo.TotalPhysicalMemory / 1000000;
			ramCounter.CategoryName = "Memory";
			ramCounter.CounterName = "Available MBytes";

			// Display
			double startX = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
			int timerIntervalMillis = 1000;

			System.Timers.Timer timer = new System.Timers.Timer(timerIntervalMillis);

			timer.Elapsed += (s, e) => {
				if (!IsEnabled) {
					timer.Stop();
					timer.Dispose();
					timer = null;
				}

				double cpuY = cpuCounter.NextValue();
				double ramY = TotalPhysicalMemory - ramCounter.NextValue();
				double x = (DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond - startX) / 1000;

				double[] coords = { x, cpuY, ramY };

				UiHelper.Synchronize(p => {
					double[] pp = (double[])p;
					CpuPoints.Add(new Point(pp[0], pp[1]));
					RamPoints.Add(new Point(pp[0], pp[2]));

					if (CpuPoints.Count > 500)
						CpuPoints.RemoveAt(0);
					if (RamPoints.Count > 500)
						RamPoints.RemoveAt(0);
				}, coords);
			};

			timer.Start();
		}
	}
}
